﻿using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;
using UnityEngine;
using System.Net;

using System.Text.RegularExpressions;
using UnityEngine.SceneManagement;

public class Utils{


	private static Rule rule = new Rule();
	private static CardBox _ = new CardBox(true, "黑桃*", "红心*");

	static Utils(){
		_.Init();
	}

	public static void checkIsInRoom(){
		if (Main.room == null || Main.room.players.Count == 0) {
			return;
		}
		checkRoomInfo ("{\"player_number\":" + Main.room.playerNum + "}");
	}

	//检测用户在哪个场次
	public static bool checkRoomInfo(object obj){
		JSONObject json = JSONObject.Create (obj.ToString());
		//人数场次
		if (json ["player_number"].IsNumber) {
			int playerNumber = int.Parse (json ["player_number"].ToString ());
			switch (playerNumber){
			case 2:
				LoadScene ("P2");
				break;
			case 3:
				LoadScene ("P3");
				break;
			case 4:
				LoadScene ("P4");
				break;
			case 5:
				LoadScene ("P5");
				break;
			case 6:
				LoadScene ("P6");
				break;
			}
			return true;
		}
		return false;
	}

	public static void LoadScene(string targetScene){
		if (SceneManager.GetActiveScene ().name == targetScene) {
			return;
		}
		SceneManager.LoadScene (targetScene);
	}


	//给在房间的用户配上状态
	public static void checkPlayerStatus(UISprite sprite,User user){
		if (user.status == PLAYER_STATUS.READY.GetHashCode ()) {
			sprite.spriteName = "Icon Ready";
		} else if (user.status == PLAYER_STATUS.BEFORE_SUBMIT.GetHashCode ()) {
			sprite.spriteName = "Icon Starting";
		} else {
			sprite.spriteName = "null";
		}
	}

	//服务端的牌型转换成本地牌型
	public static string getLocalPorker(string serverPoker){
		string paixing = null;
		if (serverPoker.Contains ("梅花")) {
			paixing = serverPoker.Contains("*") ? "C_":"C";
		} else if (serverPoker.Contains ("方块")) {
			paixing = serverPoker.Contains("*") ? "D_":"D";
		} else if (serverPoker.Contains ("红心")) {
			paixing = serverPoker.Contains("*") ? "H_":"H";
		} else if (serverPoker.Contains ("黑桃")) {
			paixing = serverPoker.Contains("*") ? "S_":"S";
		} else if (serverPoker.Contains ("王")) {
			paixing = serverPoker.Contains("*") ? "jocker_":"jocker";
		}

		if (serverPoker.Contains ("A")) {
			paixing += "1";
		} else if (serverPoker.Contains ("10")) {
			paixing += "10";
		}else if (serverPoker.Contains ("J")) {
			paixing += "11";
		} else if (serverPoker.Contains ("Q")) {
			paixing += "12";
		} else if (serverPoker.Contains ("K")) {
			paixing += "13";
		} else if (!serverPoker.Contains ("王")) {
			paixing += serverPoker.Substring (serverPoker.Length - 1, 1);
		} else {
			paixing += serverPoker.Contains("大")?"1":"2";
		}
		return paixing;
	}

	public static int comparePoker(string p1,string p2){
		string poker1 = Regex.Replace (p1, @"[^\d]*", "");
		string poker2 = Regex.Replace (p2, @"[^\d]*", "");
		if (poker1 == null || poker1 == "") {
			poker1 = p1.Contains ("A") ? "14" : p1.Contains ("J") ? "11" : p1.Contains ("Q") ? "12" : p1.Contains ("K") ? "13" : "0";
		}
		if (poker2 == null || poker2 == "") {
			poker2 = p2.Contains ("A") ? "14" : p2.Contains ("J") ? "11" : p2.Contains ("Q") ? "12" : p2.Contains ("K") ? "13" : "0";
		}
		return int.Parse(poker1).CompareTo(int.Parse(poker2));
	}

	public static string getServerPorker(string localPoker){
		string paixing = null;
		if (localPoker.Contains ("C")) {
			paixing = localPoker.Contains("_") ? "梅花*_":"梅花_";
		} else if (localPoker.Contains ("D")) {
			paixing = localPoker.Contains("_") ?"方块*_":"方块_";
		} else if (localPoker.Contains ("H")) {
			paixing = localPoker.Contains("_") ?"红心*_":"红心_";
		} else if (localPoker.Contains ("S")) {
			paixing = localPoker.Contains("_") ?"黑桃*_":"黑桃_";
		} else if (localPoker == "jocker1") {
			return "大_王";
		} else if (localPoker == "jocker2") {
			return "小_王";
		} else if (localPoker == "jocker_1") {
			return "大*_王";
		} else if (localPoker == "jocker_2") {
			return "小*_王";
		} else {
			Debug.Log ("没有找到符合的牌型");
			return null;
		}

		if (localPoker.Contains ("10")) {
			paixing += "10";
		} else if (localPoker.Contains ("11")) {
			paixing += "J";
		} else if (localPoker.Contains ("12")) {
			paixing += "Q";
		} else if (localPoker.Contains ("13")) {
			paixing += "K";
		} else if (localPoker.Contains ("1")) {
			paixing += "A";
		} else {
			paixing += localPoker.Substring (localPoker.Length-1, 1);
		}
//		Debug.Log ("牌型="+paixing);
		return paixing;
	}

//	public static bool isSpecial(){
//		var cl = new CardList();
//		AddCardsByTxt (cl, Main.user.cardList.ToArray());
//		Is_SpecialResInfo spInfo = new Is_SpecialResInfo ();
//		rule.IsSpeical (cl, out spInfo);
//
//		//如果是特殊牌型
//		return spInfo.type != "";
//	}

	public static string GetLocalTeShuSprite(string name){
		name = name.Replace ("_", "");
		if (name.Equals ("KingLong".ToLower())) {
			return "zhizunqinglong";
		} else if (name.Equals ("OneLong".ToLower())) {
			return "yitiaolong";
		} else if (name.Equals ("SixPair".ToLower())) {
			return "liuduiban";
		} else if (name.Equals ("ThreeFlush".ToLower())) {
			return "santonghua";
		} else if (name.Equals ("AllSmall".ToLower())) {
			return "quanxiao";
		} else if (name.Equals ("AllBig".ToLower())) {
			return "quanda";
		} else if (name.Equals ("ThreeStraight".ToLower())) {
			return "sanshunzi";
		} else if (name.Equals ("FourThree".ToLower())) {
			return "sitaosantiao";
		} else if (name.Equals ("ThreeFour".ToLower())) {
			return "sanfentianxia";
		} else if (name.Equals ("TwoFiveAndOneThree".ToLower())) {
			return "sanhuangwudi";
		} else if (name.Equals ("TwelveRoyal".ToLower())) {
			return "shierhuangzu";
		} else if (name.Equals ("OneFive".ToLower())) {
			return "wuzhangyiyang";
		} else if (name.Equals ("OneSix".ToLower())) {
			return "liuliudashun";
		} else if (name.Equals ("OneLong".ToLower())) {
			return "wuduisanchong";
		} else if (name.Equals ("FivePairAndOneThree".ToLower())) {
			return "couyise";
		} else if (name.Equals ("SameColor".ToLower())) {
			return "santonghuashun";
		} else if (name.Equals ("ThreeStraightFlush".ToLower())) {
			return "yitiaolong";
		} else if (name.Equals ("Three".ToLower())) {
			return "chongsan";
		} else if (name.Equals ("Fullhouse".ToLower())) {
			return "zhongdunhulu";
		}
		return "";
	}

//	public static Is_SpecialResInfo getSpecial(){
//		return getSpecial (Main.user.cardList.ToArray ());
//	}

//	public static Is_SpecialResInfo getSpecial(string[] cards){
//		var cl = new CardList();
//		AddCardsByTxt (cl, cards);
//		Is_SpecialResInfo spInfo = new Is_SpecialResInfo ();
//		rule.IsSpeical (cl, out spInfo);
//		return spInfo;
//	}

	public static void SortCard(List<string> cards){
		cards.Sort (new CardComparer());
	}


	public static void AddCardsByTxt(CardList cl, string[] txts, bool is_clear = true){
		if (is_clear)
		{
			cl.Clear();
		}
		foreach (var txt in txts)
		{
			Card card = Card.GetIns (txt);
			cl.Add(card);
		}
	}

	public static Dictionary<string,IEnumerable<string[]>> PaixingCombo(CardList cl,string[] txts){
		AddCardsByTxt (cl, txts);
		Dictionary<string,IEnumerable<string[]>> paixingCombo = new Dictionary<string, IEnumerable<string[]>> ();

		//检测对子
		paixingCombo.Add("duizi",RuleCheck(rule.CheckTwo(cl)));
		//检测顺子
		paixingCombo.Add("shunzi",RuleCheck(rule.CheckStraight(cl)));
		//检测同花
		paixingCombo.Add("tonghua",RuleCheck(rule.CheckFlush(cl)));
		//检测同花顺
		paixingCombo.Add("tonghuashun",RuleCheck(rule.CheckStraightFlush(cl)));
		//检测铁支
		paixingCombo.Add("zhadan",RuleCheck(rule.CheckFour(cl)));
		//检测三条
		paixingCombo.Add("santiao",RuleCheck(rule.CheckThree(cl)));
		//检测两对
		paixingCombo.Add("liangdui",RuleCheck(rule.CheckTwoPair(cl)));
		//检测葫芦
		paixingCombo.Add("hulu",RuleCheck(rule.CheckFullHouse(cl)));
		//检测五同
		paixingCombo.Add("wutong",RuleCheck(rule.CheckFive(cl)));

		return paixingCombo;
	}

	public static bool MidLessThanBtm (CardList mid, CardList btm)
	{
		Rule rule = new Rule ();

		return false;
	}
	static string[] mid_vs_btm_checks = new string[]{
		"Five",
		"StraightFlush",
		"Four",
		"FullHouse",
		"Flush",
		"Straight",
		"Three",
		"TwoPair",
		"Two",
		"Any"
	};
	static string[] top_vs_mid_checks = new string[]{
		"Three",
		"Two",
		"Any"
	};

	static object power = new{
		Five = 10,
		StraightFlush = 9,
		Four = 8,
		FullHouse = 7,
		Flush = 6,
		Straight = 5,
		Three = 4,
		TwoPair = 3,
		Two = 2,
		Any = 1
	};// Dictionary<string,int>();
	// true为通过，false为倒水
	public static bool MidVsBtm(CardList mid_cl,CardList btm_cl){
		InvokeRuleIsNormalResult mid_res = new InvokeRuleIsNormalResult();
		int mid_type = 0;
		for(int i = 0;i<mid_vs_btm_checks.Length;i++){
			string check_method_name = mid_vs_btm_checks[i];
			mid_res = InvokeRuleIsNormalResult.RuleIsNormal(mid_cl,5,check_method_name);
			if(mid_res.Is){
				mid_type = (int)(power.GetType().GetProperty(check_method_name).GetValue(power,null));
				break;
			}
		}
		InvokeRuleIsNormalResult btm_res  = new InvokeRuleIsNormalResult();
		int btm_type = 0;
		for(int i = 0;i<mid_vs_btm_checks.Length;i++){
			string check_method_name = mid_vs_btm_checks[i];
			btm_res = InvokeRuleIsNormalResult.RuleIsNormal(btm_cl,5,check_method_name);
			if(btm_res.Is){
				btm_type = (int)(power.GetType().GetProperty(check_method_name).GetValue(power,null));;
				break;
			}
		}
		if(btm_type > mid_type){
			return true;
		}
		if(btm_type == mid_type){
			if(btm_res.res_info.weights_value > mid_res.res_info.weights_value){
				return true;
			}
		}
		return false;
	}

	public  static bool TopVsMid(CardList top_cl,CardList mid_cl){
		InvokeRuleIsNormalResult top_res = new InvokeRuleIsNormalResult();
		int top_type = 0;
		for(int i = 0;i<top_vs_mid_checks.Length;i++){
			string check_method_name = top_vs_mid_checks[i];
			top_res = InvokeRuleIsNormalResult.RuleIsNormal(top_cl,3,check_method_name);
			if(top_res.Is){
				top_type = (int)(power.GetType().GetProperty(check_method_name).GetValue(power,null));;
				break;
			}
		}
		InvokeRuleIsNormalResult mid_res = new InvokeRuleIsNormalResult();
		int mid_type = 0;
		for(int i = 0;i<mid_vs_btm_checks.Length;i++){
			string check_method_name = mid_vs_btm_checks[i];
			mid_res = InvokeRuleIsNormalResult.RuleIsNormal(mid_cl,5,check_method_name);
			if(mid_res.Is){
				mid_type = (int)(power.GetType().GetProperty(check_method_name).GetValue(power,null));;
				break;
			}
		}
		if(mid_type > top_type){
			return true;
		}
		if(mid_type == top_type){
			if(mid_res.res_info.weights_value > top_res.res_info.weights_value){
				return true;
			}
		}
		return false;
	}

	private static IEnumerable<string[]> RuleCheck(IEnumerable<Card[]> cards){
		IEnumerable<string[]> cardsCombo = new IEnumerable<string[]> ();
		foreach (var item in cards)
		{
			string[] items = new string[item.Length];
			for (int i = 0; i < items.Length; i++) {
				items [i] = item [i].ToString ();
			}
			yield return items;
		};
	}

	//显示结果牌型
	public static UISprite ShowResultPaixing(string paixing,UISprite sprite){
		int type = int.Parse (paixing);
		//对子
		if (type == CartType.two.GetHashCode ()) {
			sprite.spriteName = "p_duizi";
		} else if (type == CartType.two_pair.GetHashCode ()) {
			sprite.spriteName = "p_liangdui";
		} else if (type == CartType.three.GetHashCode ()) {
			sprite.spriteName = "p_santiao";
		} else if (type == CartType.straight.GetHashCode ()) {
			sprite.spriteName = "p_shunzi";
		} else if (type == CartType.flush.GetHashCode ()) {
			sprite.spriteName = "p_tonghua";
		} else if (type == CartType.full_house.GetHashCode ()) {
			sprite.spriteName = "p_hulu";
		} else if (type == CartType.four.GetHashCode ()) {
			sprite.spriteName = "p_tiezhi";
		} else if (type == CartType.straight_flush.GetHashCode ()) {
			sprite.spriteName = "p_tonghuashun";
		} else if (type == CartType.five.GetHashCode ()) {
			sprite.spriteName = "p_wutong";
		} else if (type == CartType.top_three.GetHashCode ()) {
			sprite.spriteName = "p_chongsan";
		} else if (type == CartType.mid_full_house.GetHashCode ()) {
			sprite.spriteName = "p_zhongdunhulu";
		}else {
			sprite.spriteName = "p_wulong";
		}
		sprite.alpha = 0;
		sprite.gameObject.SetActive (true);

		return sprite;
	}

	public static string ToHexString ( byte[] bytes) {
		string hexString = string.Empty;
		if ( bytes != null ){                
			StringBuilder strB = new StringBuilder ();
			for ( int i = 0; i < bytes.Length; i++ ){                    
				strB.Append ( bytes[i].ToString ( "X2" ) );                
			}                
			hexString = strB.ToString ();            
		}
		return hexString;        
	}

	public static byte[] GetBytes(string hexString)
	{
		StringBuilder newString = new StringBuilder();
		char c;
		// remove all none A-F, 0-9, characters
		for (int i=0; i<hexString.Length; i++)
		{
			c = hexString[i];
			if (Uri.IsHexDigit(c))
				newString.Append(c);
		}
		// if odd number of characters, discard last character
		if (newString.Length % 2 != 0)
		{
			newString =  new StringBuilder(newString.ToString().Substring(0, newString.Length-1));
		}

		int byteLength = newString.Length / 2;
		byte[] bytes = new byte[byteLength];
		string hex;
		int j = 0;
		for (int i=0; i<bytes.Length; i++)
		{
			hex = new String(new Char[] {newString[j], newString[j+1]});
			bytes[i] = HexToByte(hex);
			j = j+2;
		}
		return bytes;
	}

	private static byte HexToByte(string hex)
	{
		byte tt = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
		return tt;
	}

	public static string[] CartToText(List<JSONObject> list){
		string[] array = new string[list.Count];
		for (int i = 0; i < list.Count; i++) {
			array [i] = list [i].str;
		}
		return array;
	}

	public static int GetScreenWidth(){
		UIRoot root = GameObject.FindObjectOfType<UIRoot>();
		if (root != null) {
			float s = (float)root.activeHeight / Screen.height;
			return Mathf.CeilToInt(Screen.width * s);

		}	
		return 0;
	}

	public static int GetScreenHeight(){
		UIRoot root = GameObject.FindObjectOfType<UIRoot>();
		if (root != null) {
			float s = (float)root.activeHeight / Screen.height;
			return  Mathf.CeilToInt(Screen.height * s);
		}
		return 0;
	}

	public static string GetIP(){
		return Network.player.ipAddress;
	}
}

class SubmitEntity{
	public string[] top;
	public string[] mid;
	public string[] btm;
	public string[] all;
	public string type;
}

class CardComparer:IComparer<string>{
	public int Compare(string x, string y) {
		if (x.Contains ("大") || x.Contains ("小") ) {
			x = x.Contains ("大") ? "17_17" : "16_16";
		}
		if (y.Contains ("大") || y.Contains ("小") ) {
			y = y.Contains ("大") ? "17_17" : "16_16";
		}

		string xString = x.Split ('_') [1];
		string yString = y.Split ('_') [1];

		int xValue = int.Parse(xString == "A" ? "14" : xString == "J"?"11":xString == "Q" ? "12" : xString == "K" ? "13":xString);
		int yValue = int.Parse(yString == "A" ? "14" : yString == "J"?"11":yString == "Q" ? "12" : yString == "K" ? "13":yString);
		//		Debug.Log (xValue.ToString() + ":" + yValue.ToString() + "result:"+xValue.CompareTo (yValue).ToString());
		return xValue.CompareTo (yValue);
	}
}
			class CardJSONComparer:IComparer<JSONObject>{
				public int Compare(JSONObject xx, JSONObject yy) {
		string x = xx.str;
		string y = yy.str;
		if (x.Contains ("大") || x.Contains ("小") ) {
			x = x.Contains ("大") ? "17_17" : "16_16";
		}
		if (y.Contains ("大") || y.Contains ("小") ) {
			y = y.Contains ("大") ? "17_17" : "16_16";
		}

		string xString = x.Split ('_') [1];
		string yString = y.Split ('_') [1];

		int xValue = int.Parse(xString == "A" ? "14" : xString == "J"?"11":xString == "Q" ? "12" : xString == "K" ? "13":xString);
		int yValue = int.Parse(yString == "A" ? "14" : yString == "J"?"11":yString == "Q" ? "12" : yString == "K" ? "13":yString);
		//		Debug.Log (xValue.ToString() + ":" + yValue.ToString() + "result:"+xValue.CompareTo (yValue).ToString());
		return xValue.CompareTo (yValue);
	}
}


public class DelayToInvoke : MonoBehaviour
{

	public static IEnumerator DelayToInvokeDo(Action action, float delaySeconds)
	{
		yield return new WaitForSeconds(delaySeconds);
		action();
	}
}


    public class InvokeRuleIsNormalResult
    {
        public bool Is = false;
        public Is_NormalResInfo res_info;
	static Rule rule = new Rule();
	public static InvokeRuleIsNormalResult RuleIsNormal(CardList card_list, int s_len, string method_name)
		{
			var res = new InvokeRuleIsNormalResult();
			
			Is_NormalResInfo res_info;
			bool is_res = false;
			switch (method_name)
			{
				case "Straight":
					is_res = rule.IsStraight(card_list, out res_info);
					break;
				case "Flush":
					is_res = rule.IsFlush(card_list, out res_info);
					break;
				case "StraightFlush":
					is_res = rule.IsStraightFlush(card_list, out res_info);
					break;
				case "Five":
					is_res = rule.IsFive(card_list, out res_info);
					break;
				case "Four":
					is_res = rule.IsFour(card_list, out res_info);
					break;
				case "Three":
					is_res = rule.IsThree(card_list, out res_info, s_len);
					break;
				case "Two":
					is_res = rule.IsTwo(card_list, out res_info, s_len);
					break;
				case "TwoPair":
					is_res = rule.IsTwoPair(card_list, out res_info);
					break;
				case "FullHouse":
					is_res = rule.IsFullHouse(card_list, out res_info);
					break;
				case "Any":
					is_res = rule.IsAny(card_list, out res_info, s_len);
					break;
				default:
					res_info = new Is_NormalResInfo();
					break;
			}
			res.Is = is_res;
			res.res_info = res_info;
			return res;
		}
    }